package com.example.myapplication.view.blood

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ArgbEvaluator
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Color
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.view.View
import android.view.animation.AccelerateInterpolator
import android.widget.FrameLayout
import androidx.databinding.DataBindingUtil
import com.example.myapplication.R
import com.example.myapplication.databinding.ViewBloodStripBinding
import com.example.myapplication.shortvideo.utils.DisplayUtils
import com.example.myapplication.util.TimeUtil
import java.util.Timer
import java.util.TimerTask


class BloodStripView(context: Context?, attrs: AttributeSet?) : FrameLayout(context!!, attrs) {
    val bloodWidth = DisplayUtils.dp2px(192)
    var mStripTotal = 0
    var mCurrentLeftStrip = 0
    var lastViewWidth = 0
    var mIsFirstOpen = true
    val mTimer by lazy { Timer() }
    var binding : ViewBloodStripBinding? = null
    init {
        binding = DataBindingUtil.bind(  View.inflate(context, R.layout.view_blood_strip, this))
    }

    fun setData(data: UserDaGuaiGiftBean) {
        if (data.stripTotal < 1) {
            binding!!.viewBg1.setBackgroundResource(R.drawable.shape_last_blood)
            binding!!.tvBlood.setTextColor(Color.WHITE)
        } else {
            binding!!.viewBg1.setBackgroundColor(getBgColor(data.stripTotal))
            binding!!.tvBlood.setTextColor(resources.getColor(R.color.color_c10e00))
        }

        binding!!.tvBlood.visibility = if (data.surplusBlood > 0) {
            View.VISIBLE
        } else {
            View.GONE
        }
        binding!!.tvBlood.text = "x${data.surplusBlood}"

        binding!!.viewBg2.setBackgroundColor(getBgColor(data.stripTotal + 1))

        val currentViewWidth = (bloodWidth * (data.currentLeftStrip.toFloat() / 100)).toInt()
        val layoutParams2 =  binding!!.viewBg2.layoutParams
        layoutParams2.width = currentViewWidth
        binding!!.viewBg2.layoutParams = layoutParams2

        if (!mIsFirstOpen) {
            //本次减少的血条
            val reduceStrip = mStripTotal - data.stripTotal
            if (data.stripTotal > 0 && reduceStrip > 0) {
                addBloodAnimeData(lastViewWidth, currentViewWidth, reduceStrip)
            } else {
                addBloodAnimeData(currentViewWidth, lastViewWidth, 0)
            }
        }

        val layoutRunaway =  binding!!.tvRunawayReward.layoutParams  as LayoutParams
        layoutRunaway.marginStart =  DisplayUtils.dp2px(10)
        binding!!.tvRunawayReward.layoutParams= layoutRunaway

        //todo
        binding!!.tvEnergyreward.visibility = View.VISIBLE
        binding!!.imgEnergyreward.visibility = View.VISIBLE
        binding!!.tvEnergyreward.text = "15000"

        //todo
        binding!!.tvTips.text = "打死我最低可得8888能量哦！"

        binding!!.tvRunawayReward.text = "打死我最低可得8888能量哦！"

        mHandler.removeMessages(1)
//        mHandler.sendEmptyMessageDelayed(1, 2000);
        mStripTotal = data.stripTotal
        mCurrentLeftStrip = data.currentLeftStrip
        lastViewWidth = currentViewWidth
        mIsFirstOpen = false
    }


    val mHandler: Handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                binding!!.tvEnergyreward.visibility = View.GONE
                binding!!.imgEnergyreward.visibility = View.GONE
            }
        }
    }


    private fun setRefreshTask(serverTime: Long) {
        val offSetTime = System.currentTimeMillis() - serverTime
        val delay = TimeUtil.getTargetTime(offSetTime, "05:00:00")
        mTimer.schedule(object : TimerTask() {
            override fun run() {
                //todo

            }
        }, delay)
    }

    fun addBloodAnimeData(leftPoint: Int, rightPoint: Int, bloodStrip: Int) {
        if (bloodStrip > 0) {
            for (i in 0..bloodStrip) {
                if (i == 0) {
                    createBloodView(0, bloodWidth - leftPoint)
                } else if (i == bloodStrip) {
                    createBloodView(rightPoint, 0)
                } else {
                    createBloodView(0, 0)
                }
            }
        } else {
            createBloodView(leftPoint, bloodWidth - rightPoint)
        }
    }


    private fun createBloodView(marginStart: Int, marginEnd: Int): View {
        val bloodView = View(context)
        val layout = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
        layout.marginStart = marginStart
        layout.marginEnd = marginEnd
        bloodView.layoutParams = layout
        bloodView.setBackgroundColor(Color.WHITE)
        binding!!.viewBg3.addView(bloodView)
        startAnime(bloodView)
        return bloodView
    }


    private fun startAnime(bloodView: View) {
        val animator = ValueAnimator.ofInt(
            Color.parseColor("#ffffff"),
            Color.parseColor("#888888")
        )
        animator.setEvaluator(ArgbEvaluator())
        animator.interpolator = AccelerateInterpolator()
        animator.duration = 1000
        animator.addUpdateListener { animation ->
            val value = animation.animatedValue as Int
            bloodView.setBackgroundColor(value)
        }

        val alpha = ObjectAnimator.ofFloat(bloodView, "alpha", 1f, 0f).setDuration(1000)
        alpha.start()

        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationStart(animation: Animator) {
            }

            override fun onAnimationRepeat(animation: Animator) {
            }

            override fun onAnimationCancel(animation: Animator) {
                binding!!.viewBg3.removeView(bloodView)
            }

            override fun onAnimationEnd(animation: Animator) {
                binding!!.viewBg3.removeView(bloodView)
            }
        })
        animator.start()
    }

    private fun getBgColor(step: Int): Int {
        return when (step) {
            5 -> Color.parseColor("#FFE057")
            4 -> Color.parseColor("#FFB732")
            3 -> Color.parseColor("#BBFA79")
            2 -> Color.parseColor("#79EBFA")
            1 -> Color.parseColor("#A59FFC")
            else -> Color.parseColor("#00000000")
        }
    }


    fun close() {
        mIsFirstOpen = true
        mHandler.removeMessages(1)
        mTimer.cancel()
    }
}